Stacks

PDF versionPDF version

#include<stdio.h>  //header files
#include<conio.h>

void push();  //forward declaration
void pop();
void display();

char ans;  //global variables declaration
int top=-1,ch,i,ele;
int stack[30];

void main()
{
 clrscr();
 do
 {
  clrscr();
  printf("\n\n What do you want to do? ");
  printf("\n\n 1 : INSERT");
  printf("\n 2 : DELETE");
  printf("\n 3 : DISPLAY");
  printf("\n 4 : EXIT");
  printf("\n\n Enter your choice here => ");
  scanf("%d",&ch);

  switch(ch)
  {
   case 1:{
    push();
    break;
   }
   case 2:{
    pop();
    break;
   }
   case 3:{
    display();
    break;
   }
   case 4: exit();
   default: printf("\n\n You have entered a wrong choice.");
  }
  printf("\n\n Do you want to continue? (y/n): ");
  flushall();
  scanf("%c",&ans);
 }while(ans=='y');

 getch();
}

void push()
{
 if(top==-1)
  printf("\n\n Stack is empty.");

 printf("\n\n Enter the element: ");
 scanf("%d",&ele);
 top=top+1;
 stack[top]=ele;
 printf("\n\n Element %d has been inserted.",ele);
}

void pop()
{
 printf("\n\n Element %d has been deleted.",stack[top]);
 top=top-1;
 if(top==-1)
  printf("\n\n Stack is empty.");
}

void display()
{
 if(top==-1)
  printf("\n\n Stack is empty.");
 else
 {
 printf("\n\n The Resultant Stack: ");
 for(i=0;i<=top;i++)
  printf("%d",stack[i]);
 }
}